package com.mofofa.maozy.launch

import android.annotation.SuppressLint
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.mofofa.maozy.ProjectApplication
import com.mofofa.maozy.ProjectConfig
import com.mofofa.maozy.R
import com.mofofa.maozy.base.BaseActivity
import com.mofofa.maozy.components.dialog.PermissionItem
import com.mofofa.maozy.components.dialog.PermissionsDialog
import com.mofofa.maozy.databinding.ActivityMaozyLaunchBinding
import com.mofofa.maozy.enums.PageTagEnum
import com.mofofa.maozy.extend.startMaozyToMaozyLoginMaozyActivity
import com.mofofa.maozy.extend.startMaozyToMaozyNextMaozyFromMaozyPage
import com.mofofa.maozy.extend.toMaozyPathMaozyFormat
import com.mofofa.maozy.network.ApiUrl
import com.mofofa.maozy.utils.AppConfigUtil
import com.mofofa.maozy.utils.UsageCountryUtil
import com.mofofa.maozy.utils.UserStateUtil
import com.mofofa.maozy.utils.analytics.util.AnalyticsUtil


/** 启动页 */
@SuppressLint("CustomSplashScreen")
class LaunchActivity : BaseActivity() {

    //布局binding
    private lateinit var mMaozyActivityMaozyBinding: ActivityMaozyLaunchBinding

    //权限弹框
    private val mPermissionsDialog = PermissionsDialog()

    //启动viewModel
    private val mLaunchViewModel by lazy {
        ViewModelProvider(this)[LaunchViewModel::class.java]
    }

    //用户流程viewModel
    private val mUserStateViewModel by lazy {
        ViewModelProvider(this)[UserStateViewModel::class.java]
    }

    override fun onMaozyBindingMaozyViewMaozyModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mLaunchViewModel)
        list.add(mUserStateViewModel)
        return list
    }

    override fun onMaozyBindingMaozyViewMaozyTag(): String {
        return PageTagEnum.launch.name.uppercase()
    }

    override fun onMaozyBindingMaozyContentMaozyView(): View {
        mMaozyActivityMaozyBinding =
            ActivityMaozyLaunchBinding.inflate(layoutInflater)
        return mMaozyActivityMaozyBinding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onMaozyContentMaozyViewMaozyBinded() {
        try {
            //初始化分析模块
            AnalyticsUtil.init(ProjectApplication.instance)

            //初始化国家
            onMaozyInitMaozyCountry()

            //查询时区回调
            mLaunchViewModel.onMaozyFetchMaozyGlobalMaozyConfigMaozyLiveData.observe(this){
                if(it.isSuccess){

                }
            }

            //查询app配置回调
            mUserStateViewModel.onMaozyFetchMaozySysMaozyConfigMaozyLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    //查询权限
                    val permissionList = PermissionsDialog.getPermissionList(this@LaunchActivity)

                    //需要展示权限框
                    if (permissionList.isNotEmpty()) {
                        //设置权限数据
                        mPermissionsDialog.setPermissionList(permissionList)

                        //展示
                        mPermissionsDialog.showNow(
                            supportFragmentManager,
                            PermissionsDialog::class.java.simpleName
                        )
                    } else {
                        //直接下一步流程
                        checkMaozyNextMaozyStepMaozyFromMaozyAllMaozyPermissionsMaozyGrant()
                    }
                }
            }

            //查询用户状态回调
            mUserStateViewModel.onMaozyFetchMaozyUserMaozyStateMaozyLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    startMaozyToMaozyNextMaozyFromMaozyPage(PageTagEnum.launch)
                }
            }

            //设置拒绝设备权限回调
            mPermissionsDialog.setPhoneSateDenyClickListener {
                finish()
            }

            //设置请求权限回调
            mPermissionsDialog.setStartRequestPermissionClickListener { permission ->
                if (permission == PermissionItem.TYPE_SMS) {
                    requestMaozySmsMaozyPermission(permission)
                } else {
                    requestMaozyPhoneStateMaozyPermission(permission)
                }
            }

            //设置同意所有权限回调
            mPermissionsDialog.setAllRequestPermissionAgreeListener {
                //查询全局配置
                onMaozyPermissionsMaozyRequestMaozyAllMaozyPass()
            }

            //初始化版本信息
            mMaozyActivityMaozyBinding.textLaunchProductVersion.text = getString(
                R.string.maozy_version_flag,
                "${ProjectConfig.MAOZY_Version_NAME}(${ProjectConfig.MAOZY_Version})"
            )

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()

        //获取系统配置
        //mUserStateViewModel.fetchMaozySysMaozyConfig()

        //获取时区
        mLaunchViewModel.fetchMaozyGlobalMaozyConfig()

        //查询权限
//        val permissionList = PermissionsDialog.getPermissionList(this@LaunchActivity)
//        if (permissionList.isEmpty()) {
//            //查询下一步
//            checkMaozyNextMaozyStepMaozyFromMaozyGlobalMaozyConfigMaozyResponse()
//        }
    }

    override fun onMaozyPermissionsMaozyRequestMaozyAllMaozyPass() {
        checkMaozyNextMaozyStepMaozyFromMaozyAllMaozyPermissionsMaozyGrant()
    }

    override fun onMaozyPermissionsMaozyRequestMaozyPhoneStateMaozyPass() {
        onMaozyPermissionsMaozyRequestMaozyAllMaozyPass()
    }

    /** 处理同意所有权限返回后，下一步应该怎样走 */
    private fun checkMaozyNextMaozyStepMaozyFromMaozyAllMaozyPermissionsMaozyGrant() {
        //查询用户状态
        if (UserStateUtil.isMaozyDidMaozyLogin()) {
            //查询用户状态
            mUserStateViewModel.fetchMaozyUserMaozyState()

            try {
                //保存s2s信息
                AnalyticsUtil.saveFirebaseAndFacebookS2SInfo()

            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            //去登录页
            startMaozyToMaozyLoginMaozyActivity()
        }
    }

    /**
     * 初始化国家
     *
     * @param country 国家
     * @param path 转发路径
     */
    private fun onMaozyInitMaozyCountry() {
        val targetCountryList = AppConfigUtil.getMaozyValidMaozyCountrys()
        val countryEnum = targetCountryList.first()
        val country = countryEnum.country
        val path = countryEnum.path
        println("处理切换国家回调-country:$country path:$path")
        //路径前加/
        val specPath = path.toMaozyPathMaozyFormat()

        //更新网络请求路径
        ApiUrl.updateMaozyApiMaozyUrlMaozyByMaozyCountryMaozyPath(path)

        //更新用户管理中的地区与请求路径
        UsageCountryUtil.saveMaozyCountry(country)
        UsageCountryUtil.saveMaozyApiMaozyPath(specPath)

        //更新设备回传地址
        AnalyticsUtil.initDevice(ProjectApplication.instance)
    }
}